import { login, logout } from '@/api/login'
import { getToken, setToken, removeToken, isAdmin, getUsername, setUsername, removeUsername } from '@/utils/auth'
import { Message } from 'element-ui'

const user = {
  state: {
    token: getToken(),
    username: getUsername()
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USERNAME: (state, username) => {
      state.username = username
    }
  },

  actions: {
    // 登录
    Login({
      commit
    }, userInfo) {
      const id = userInfo.id.trim()
      return new Promise((resolve, reject) => {
        login(id, userInfo.password).then(res => {
          const data = res.data.data
          const result = isAdmin(data)
          if (result) {
            commit('SET_TOKEN', data.Authorization)
            commit('SET_USERNAME', data.user.name)
            setToken(data.Authorization)
            setUsername(data.user.name)
            resolve()
          } else {
            Message({
              message: '权限不足，无法登录',
              type: 'error',
              duration: 5 * 1000
            })
            reject()
          }
        }).catch(err => {
          reject(err)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          commit('SET_TOKEN', '')
          commit('SET_USERNAME', '')
          removeToken()
          removeUsername()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_USERNAME', '')
        removeToken()
        removeUsername()
        resolve()
      })
    }
  }
}

export default user
